/**
 *  represent the class that handles user log in to the system
 *  and return th
 * 
 */

package source;

import activejdbc.Model;

public class LoginController {
	

	public LoginController() {
	}
	
	public static Object[] checkLogin(String username, String password) {
		Doctor d = (Doctor)Doctor.findFirst("username = ?", username);
		Nurse n = (Nurse)Nurse.findFirst("username = ?", username);
		Patient p = (Patient)Patient.findFirst("username = ?", username);
		SystemAdministrator s = (SystemAdministrator)SystemAdministrator.findFirst("username = ?", username);
		Object[] returnArray = new Object[2];
		if(s != null) {
			if(LoginController.checkPassword(password, s)) {
				returnArray[0] = 'a';
				returnArray[1] = s;
			}
		} else if(p != null) {
			if(LoginController.checkPassword(password, p)) {
				returnArray[0] = 'p';
				returnArray[1] = p;
			}
		} else if(n != null) {
			if(LoginController.checkPassword(password, n)) {
				returnArray[0] = 'n';
				returnArray[1] = n;
			}
		} else if(d != null) {
			if(LoginController.checkPassword(password, d)) {
				returnArray[0] = 'd';
				returnArray[1] = d;
			}
		}
		return returnArray;
	}
	
	public static boolean checkPassword(String password, Model m) {
		if(password.equals(m.get("password")) && !m.getBoolean("suspended")) {
			return true;
		} else {
			long failedLogins = m.getLong("failed_logins");
			failedLogins++;
			m.set("failed_logins", failedLogins);
			if(failedLogins % 3 == 0) {
				m.set("suspended", true);
			}
			m.saveIt();
			return false;
		}
	}
}
